package com.udp;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ChatterClient extends Thread {

    private DatagramSocket s;
    private InetAddress hostAddress;
    private byte[] buf = new byte[1000];
    private DatagramPacket dp = new DatagramPacket(buf, buf.length);

    public ChatterClient() {
        try {
            s = new DatagramSocket();
            // localhost 、127.0.0.1、 
            hostAddress = InetAddress.getByName("localhost");
        } catch (UnknownHostException e) {
            System.err.println("Cannot find host");
            System.exit(1);
        } catch (SocketException e) {
            System.err.println("Can't open socket");
            e.printStackTrace();
            System.exit(1);
        }
        System.out.println("ChatterClient starting");
    }
    public void run() {
        try {
                String outMessage = new String("客户端data".getBytes(),"UTF-8") ;
                s.send(new DatagramPacket(outMessage.getBytes(), outMessage.getBytes().length, hostAddress, ChatterServer.INPORT));
                s.receive(dp);
                //客户端收到服务端的数据
                String rcvd = "客户端收到数据:"+ new String(dp.getData(), 0, dp.getLength(),"UTF-8");
                System.out.println(rcvd);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static void main(String[] args) {
    	final ChatterClient client=new ChatterClient();
    	client.start();
    	for(int i=0;i<10;i++){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
    	}		
    }
}
